import { aboutUser } from "../../store";
import { unLockApi } from "../../api/user";

const { getPlayletManager } = tt;

let adTimer = null;

Component({
  inject: ["chargeTap"],

  data: { adUnitId: "", adTime: 5, adType: "", emitTimesCharge: 0, userInfo: {} },

  observers: {
    // 点击组件 A 的 button 后，触发该监听器的执行
    chargeTap(val) {
      this.setData({
        emitTimesCharge: val,
      });
    },
  },

  ready() {
    adTimer = setInterval(() => {
      this.setData({ adTime: this.data.adTime - 1 });

      if (this.data.adTime == 0) {
        this.setData({ adTime: 5, adTimer: null });
        clearInterval(adTimer);
        this.showAd();
      }
    }, 1000);
  },

  async attached() {
    this.setData({ userInfo: aboutUser.getUserInfo() });

    const userInfo = aboutUser.getUserInfo();
    this.setData({ userInfo });

    const pm = getPlayletManager();
    this.pm = pm;
    this.ad = tt.createRewardedVideoAd({ adUnitId: this.data.userInfo.adUnitId });

    pm.onPlay(() => {
      console.log("在charge中监听onPlay");
    });

    // 监听视频播放完成
    this.ad.onClose((data) => {
      tt.hideLoading();
      if (data.isEnded) {
        this.pm.toggleCustomDialog("close");
        this.pm.setCurrentUnlock();
        this.unlockApiFun();
        aboutUser.addPointFun("watchGg");
      } else {
        console.log("未观看完视频");
        tt.showToast({ icon: "none", title: "未观看完视频" });
      }
    });

    //记录解锁信息
  },

  detached() {
    this.setData({ adTime: 5, adTimer: null });
    clearInterval(adTimer);

    if (this.ad) {
      this.ad.destroy();
    }
  },

  methods: {
    unLockFun() {},

    /** 解锁后传参数到后端 */
    unlockApiFun() {
      this.pm.getPlayletInfo().then((res) => {
        const pages = getCurrentPages();
        const options = pages[pages.length - 1].options; // 获取当前页面

        unLockApi({ vid: options.vid, uid: this.data.userInfo.userId, vNum: res.seq });
      });
    },

    showAd() {
      tt.showLoading({ title: "视频拉起中", mask: true });
      this.ad.show();
    },

    closeAd() {
      this.pm.toggleCustomDialog("close");
    },

    emitInfoToParent() {
      const instance = this.selectOwnerComponent();
      instance.showOnTimeUpdateChange("charge");
    },
  },
});
